package com.food.user.consumer;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.food.user.entity.FoodMonthSale;
import com.food.user.entity.Order;
import com.food.user.entity.OrderFood;
import com.food.user.service.FoodMonthSaleService;
import com.food.user.service.OrderFoodService;
import com.food.user.service.OrderService;
import com.food.user.util.DateUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.List;

@Component
@RocketMQMessageListener(consumerGroup = "NumCount",topic = "count_num")
public class CountNum  implements RocketMQListener<String> {
    @Autowired
    private OrderFoodService orderFoodService;
    @Autowired
    private FoodMonthSaleService foodMonthSaleService;
    @Autowired
    private OrderService orderService;
    @Override
    public void onMessage(String s) {
        //当前年月
        YearMonth yearMonth=YearMonth.from(LocalDate.now());
        System.out.println("count");
        //得到商铺id
        Order order = orderService.getById(s);

        List<OrderFood> orderFoods = orderFoodService.list(new QueryWrapper<OrderFood>().eq("order_food_order_num", s));
        for (OrderFood orderFood : orderFoods) {
            Long foodId = orderFood.getOrderFoodFoodId();
            FoodMonthSale one = foodMonthSaleService.getOne(new QueryWrapper<FoodMonthSale>()
                    .eq("food_month_sale_food_id", foodId)
                    .eq("food_month_sale_date_str", yearMonth));
            if (one==null){
                //说明是第一次卖该食品 走添加
                FoodMonthSale foodMonthSale = new FoodMonthSale();
                foodMonthSale.setFoodMonthSaleStoreId(order.getOrderStoreId());
                foodMonthSale.setFoodMonthSaleFoodId(foodId);
                foodMonthSale.setFoodMonthSaleDateStr(yearMonth.toString());
                foodMonthSale.setFoodMonthSaleCount(orderFood.getOrderFoodCount());
                foodMonthSale.setFoodMonthSaleFinalDate(DateUtils.parseString(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss"));
                foodMonthSaleService.save(foodMonthSale);
            }else {
                //走修改
                one.setFoodMonthSaleCount(one.getFoodMonthSaleCount()+orderFood.getOrderFoodCount());
                one.setFoodMonthSaleFinalDate(DateUtils.parseString(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss"));
                foodMonthSaleService.updateById(one);
            }
        }
    }
}
